<!--微信自定义菜单-->
<template>
  <div id="wechatMenu" class="app-container">
    <div class="flex-row">
      <div class="wechat-menu-container">
        <div class="weixin-hd">
          <div class="weixin-title">
            <el-form :model="listQuery" :inline="true">
              <el-form-item>
                <application-key-select ref="applicationKeySelect" v-model="listQuery.appId" :type="listQuery.type" />
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="weixin-menu  clearfix">
          <div v-for="firstItem in menuData" :key="firstItem.id" class="menu_bottom">
            <div class="menu_item el-icon-s-fold" @click="clickFirstMenu(firstItem)">{{ firstItem.name }}</div>
            <div v-show="activeMenuIndex===firstItem.id" class="submenu">
              <div v-for="secondItem in firstItem.children" :key="secondItem.id" class="subtitle menu_bottom">
                <div class="menu_subItem" @click="clickSecondMenu(secondItem)">{{ secondItem.name }}</div>
              </div>
              <div v-if="firstItem.children.length<5" class="menu_bottom"><i class="el-icon-plus" @click="clickAddSecondMenu(firstItem.id)" /></div>
            </div>
          </div>
          <div v-if="menuData.length<3" class="menu_bottom" @click="clickAddFirstMenu(0)"><i class="el-icon-plus" /></div>
        </div>
        <div class="save_div">
          <el-button v-if="menuRecord.name" type="primary" :loading="buttonLoading" @click="status==='create'?createData():updateData()">保存</el-button>
          <el-button v-if="menuData.length>0" type="primary" :loading="buttonLoading" @click="generalMenu">发布</el-button>

        </div>
      </div>
      <div class="wechat-menu-form-container">
        <template v-if="menuRecord.name">
          <div class="common-title m-b-20">
            <h2 class="bold">{{ menuRecord.name }}</h2>
            <el-link v-if="menuRecord.id" type="danger" :underline="false" @click="removeRecord(menuRecord)">删除菜单</el-link>
          </div>
          <div v-if="menuRecord.children" class="m-b-20 common-tips">
            已添加子菜单，仅可设置菜单名称。
          </div>
          <el-form ref="menuForm" :rules="rules" :model="menuRecord" label-position="right" label-width="120px">
            <el-form-item label="菜单名称:" prop="name">
              <el-input v-model="menuRecord.name" maxlength="8" show-word-limit placeholder="仅支持中英文和数字，字数不超过4个汉字或8个字母" />
            </el-form-item>
            <template v-if="!menuRecord.children || menuRecord.children.length===0">
              <el-form-item label="类型:" prop="type">
                <el-select v-model="menuRecord.type" placeholder="请选择" style="width:100%" @change="changeType">
                  <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item v-if="menuRecord.type!=null" :label="menuRecordTypeLabel" prop="eventValue">
                <el-input v-model="menuRecord.eventValue" :disabled="menuRecord.type=='click'" />
              </el-form-item>
            </template>
            <el-form-item label="排序:" prop="orders">
              <el-input-number v-model="menuRecord.orders" placeholder="请输入排序" show-word-limit :max="99" style="width:100%" />
            </el-form-item>
            <el-form-item>
              <material-selection :app-id="listQuery.appId" />
            </el-form-item>

          </el-form>
        </template>
        <div v-if="!menuRecord.name" class="conmmon-container-main flex-main" style="background-color: #fff;text-align: center;padding-top: 15%;font-weight: bold;">
          请先选择菜单
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import applicationKeySelect from '../applicationKeySelect'
import MaterialSelection from './components/materialSelection.vue'
export default {
  components: { applicationKeySelect, MaterialSelection },
  data() {
    return {
      wechatConfigRecords: {},
      listQuery: {
        appId: '',
        type: 1
      },
      activeMenuIndex: null,
      articleListQuery: {
        page: 1,
        limit: 10,
        sort: '-gmtModified',
        type: 1
      },
      typeOptions: [
        { value: 'click', label: '发送消息' },
        { value: 'view', label: '跳转网页' }
      ],
      parentOptions: [],
      columns: [
        { text: '名称', dataIndex: 'name' },
        { text: '类型', dataIndex: 'type' },
        { text: '菜单值', dataIndex: 'eventValue' }
      ],
      menuData: [],
      status: 'create',
      buttonLoading: false,
      menuRecord: {},
      menuRecordTypeLabel: 'Key',
      rules: {
        name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        pid: [{ required: true, message: '请选择所属上级', trigger: 'blur' }]
      },

      dialogTableVisible: false,
      activeName: 'imageText-1',
      selectedArticles: [],
      selectedMenu: [],
      articleTypeOptions: [{ value: 1, label: '图文' }, { value: 2, label: '图片' }, { value: 3, label: '音频' }, { value: 4, label: '视频' }],
      total: 0,
      curentTab: 'imageText-1',
      articleList: [],
      curentSelection: []
    }
  },
  watch: {
    'listQuery.appId': function(val) {
      this.getWechatConfig()
      this.fetchData()
    }
  },
  created() {
  },
  methods: {
    async generalMenu() {
      try {
        await this.$store.dispatch('wechatMenuGenerate', this.listQuery.appId)
        this.msgSuccess('创建成功')
      } catch (err) {
        console.log(err)
      }
    },
    async getWechatConfig() {
      const response = await this.$store.dispatch('applicationKeyConfigGetByAppId', this.listQuery.appId)
      if (response == null) {
        this.msgWarning('请先配置相关信息！')
        return
      }
      this.wechatConfigRecords = response
    },
    async fetchData() {
      const response = await this.$store.dispatch('wechatMenuTreeTable', this.listQuery)
      this.menuData = response
    },
    clickFirstMenu(value) {
      this.activeMenuIndex = value.id
      this.menuRecord = Object.assign({}, value) // copy obj
      this.status = 'update'
    },
    clickSecondMenu(value) {
      this.menuRecord = Object.assign({}, value) // copy obj
      this.status = 'update'
    },
    clickAddFirstMenu(value) {
      this.menuRecord = { pid: value, name: '菜单名称', orders: 99 }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    clickAddSecondMenu(value) {
      this.menuRecord = { pid: value, name: '子菜单名称', orders: 99 }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['menuForm'].clearValidate()
      })
    },
    changeType() {
      if (this.menuRecord.type === 'view') {
        const menuRecord = Object.assign({}, this.menuRecord) // copy obj
        menuRecord.eventValue = ''
        this.menuRecord = menuRecord
        this.menuRecordTypeLabel = '跳转路径'
      }
      if (this.menuRecord.type === 'click') {
        const menuRecord = Object.assign({}, this.menuRecord) // copy obj
        menuRecord.eventValue = new Date().getTime() + ''
        this.menuRecord = menuRecord
        // this.menuRecord.eventValue = new Date().getTime() + "";
        this.menuRecordTypeLabel = 'Key'
      }
    },

    createData() {
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          this.menuRecord = {
            ...this.menuRecord,
            appId: this.listQuery.appId
          }
          this.$store.dispatch('wechatMenuSave', this.menuRecord).then(response => {
            this.msgSuccess('创建成功')
            this.handleFilter()
          }).catch(() => {
          })
        }
      })
    },

    updateData() {
      this.$refs['menuForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.menuRecord)
          delete tempData.children
          delete tempData._parent
          this.$store.dispatch('wechatMenuUpdate', tempData).then(response => {
            this.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
          })
        }
      })
    },

    removeRecord(row) {
      const ids = [row.id]
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('wechatMenuRemove', ids).then(response => {
          this.handleFilter()
          this.msgSuccess('删除成功!')
        }).catch(() => {})
      }).catch(() => {})
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },

    /**
     * 打开关联文章对话框
     */
    relatedArticles(obj) {
      this.activeName = 'imageText-1'
      this.articleListQuery.type = 1
      this.selectedMenu = obj
      this.dialogTableVisible = true
      this.getArticlePage()
      setTimeout(() => {
        this.getArticlesByMenuId()
      }, 500)
    },
    getArticlePage() {
      const $this = this
      $this.$store.dispatch('wechatArticlePage', $this.articleListQuery).then(response => {
        $this.articleList = response.records
        $this.total = response.total
      })
    },
    // 全选
    imageTextChange(value) {
      const $this = this
      $this.curentSelection = []
      $this.curentSelection = value
      const articleArrWithCurType = []
      $this.selectedArticles.forEach(function(item, index) {
        if (item.resourceType === $this.activeName.split('-')[1]) {
          articleArrWithCurType.push(item)
        }
      })
      setTimeout(function() {
        if ($this.curentSelection.length > 0) {
          $this.curentSelection.forEach(function(item, index) {
            let num = 0
            articleArrWithCurType.forEach(function(i, j) {
              if (item.id === i.id) {
                num += 1
              }
            })
            if (num === 0) {
              $this.selectedArticles.push(item)
            }
          })
          articleArrWithCurType.forEach(function(item, index) {
            let num = 0
            $this.curentSelection.forEach(function(i, j) {
              if (item.id === i.id) {
                num += 1
              }
            })
            if (num === 0) {
              $this.selectedArticles.forEach(function(a, b) {
                if (a.id === item.id) {
                  $this.selectedArticles.splice($this.selectedArticles.indexOf(a), 1)
                }
              })
            }
          })
        }
      }, 400)
    },
    // 文章类型改变事件
    changeArticleType(value) {
      this.articleListQuery.page = 1
      this.articleListQuery.type = value
      this.getArticlePage()
    },
    // 保存
    menuArticleSave() {
      const $this = this
      const articleIds = []
      $this.selectedArticles.forEach(function(item, index) {
        articleIds.push(item.id)
      })
      const params = { menuId: $this.selectedMenu.menuId + '-' + $this.selectedMenu.eventValue, articleIds: articleIds }
      $this.$store.dispatch('menuArticleSave', params).then(response => {
        $this.dialogTableVisible = false
        $this.msgSuccess(response)
      })
    },
    // 标签改变事件
    handleClick(tag, event) {
      const $this = this
      $this.curentTab = tag.name
      $this.articleListQuery.type = tag.name.split('-')[1]
      $this.articleListQuery.page = 1
      $this.getArticlePage()
      // 默认选中
      setTimeout(function() {
        $this.selectedArticlesData()
      }, 500)
    },
    selectedArticlesData() {
      const $this = this
      if ($this.curentTab === 'imageText-1') {
        $this.selectedData(1)
      } else if ($this.curentTab === 'image-2') {
        $this.selectedData(2)
      } else if ($this.curentTab === 'audio-3') {
        $this.selectedData(3)
      } else if ($this.curentTab === 'video-4') {
        $this.selectedData(4)
      }
    },
    // 遍历选中数据
    selectedData(resourceType) {
      const $this = this
      $this.articleList.forEach(function(item, index) {
        $this.selectedArticles.forEach(function(i, j) {
          if (i.id === item.id & i.resourceType === resourceType) {
            $this.$refs.imageTextTable.toggleRowSelection(item, true)
          }
        })
      })
    },
    // 默认选中
    getArticlesByMenuId() {
      const $this = this
      $this.$store.dispatch('getArticlesByMenuId', $this.selectedMenu.menuId).then(response => {
        $this.selectedArticles = response
        $this.articleList.forEach(function(i, j) {
          $this.selectedArticles.forEach(function(item, index) {
            if (item.id === i.id & item.resourceType === 1) {
              $this.$refs.imageTextTable.toggleRowSelection(i, true)
            }
          })
        })
      })
    },
    // 移除标签
    handleCloseTag(articleId) {
      const $this = this
      $this.selectedArticles.forEach(function(item, index) {
        if (item.id === articleId) {
          $this.selectedArticles.splice($this.selectedArticles.indexOf(item), 1)
        }
      })
      $this.articleList.forEach(function(item, index) {
        if (item.id === articleId) {
          $this.$refs.imageTextTable.toggleRowSelection(item, false)
        }
      })
    }
  }
}
</script>
<style lang="scss" >
#wechatMenu{
  background-color: #fff;
  padding: 20px;
  .wechat-menu-container{
    display: inline-block;
    width: 350px;
    height: 715px;
    background: url(~@/assets/images/iphone_backImg.png) no-repeat;
    background-size: 100% auto;
    padding: 518px 25px 88px;
    position: relative;
    box-sizing: border-box;
    .weixin-hd{
      color: #fff;
      text-align: center;
      position: relative;
      bottom: 426px;
      left: 0;
      width: 300px;
      height: 64px;
      background: transparent url(~@/assets/images/iphone_head.png) no-repeat 0 0;
      background-position: 0 0;
      background-size: 100%;
    }
    .weixin-title{

      width: 100%;
      text-align: center;
      position: absolute;
      top: 24px;
      left: 0;
      .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
        margin-bottom: 0px;
      }
      .el-input__inner{
        background-color: #ffffff00;
        color: #fff;
        font-size: 14px;
        border: 0px;
      }
    }
    .weixin-menu {
      background: transparent url() no-repeat 0 0;
      padding-left: 43px;
      font-size: 12px;
      .menu_bottom {
        position: relative;
        display: inline-block;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        width: 85.5px;
        height: inherit;
        line-height: 46px;
        text-align: center;
        border: 1px solid #ebedee;
        background-color: #fff;
        cursor: pointer;
      }
      .menu_item {
        height: 44px;
        line-height: 44px;
        text-align: center;
        box-sizing: border-box;
        width: 100%;
      }
      .menu_bottom:hover{
        background-color: #ecf5ff;
        border: 1px solid #ecf5ff;
      }
      .submenu {
        position: absolute;
        width: 85.5px;
        bottom: 45px;
      }

    }
    .save_div{
      margin-top: 15px;
      text-align: center;
    }
  }
  .wechat-menu-form-container{
    margin-left: 20px;
    flex: 1;
  }
}
</style>
